﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using IterationLife.Datas;
using IterationLife.Extensions.MvcApi;
using IterationLife.Extensions.Qiniu;
using Json.Net;
using Util.Datas.Ef;
using Util.Iocs;
using Util.Logs;

namespace IterationLife.Mobile.CampusFootball.Student.ApiGateway
{
    /// <summary>
    /// 应用程序全局设置
    /// </summary>
    public class MvcApplication : HttpApplication
    {
        /// <summary>
        /// 启动应用程序
        /// </summary>
        protected void Application_Start()
        {
            WriteLog("Application_Start准备启动");
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            Ioc.RegisterMvc(typeof(MvcApplication).Assembly, new IocConfig());
            UnitOfWork.Init(new ApplicationUnitOfWork());
            QiNiu.Init();
            WriteLog("Application_Start启动完成");
        }

        /// <summary>
        /// 应用程序错误处理
        /// </summary>
        protected void Application_Error(object sender, EventArgs e)
        {
            var lastError = Server.GetLastError();
            WriteLog(lastError);
            if (lastError is HttpException)
            {
                var statusCode = (lastError as HttpException).GetHttpCode();
                Response.StatusCode = statusCode;
                Response.ContentType = "application/json";
                var result = new MvcApiResult<object>();
                switch (statusCode)
                {
                    case 404:
                        result.Message = "Not Found";
                        break;
                    default:
                        result.Message = "Unknown Error";
                        break;
                }
                var json = JsonConvert.SerializeObject(result);

                Response.Write(json);
                Response.End();
            }

            //Response.Redirect( @"~/error" );
            //Server.ClearError();
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        private void WriteLog(string caption)
        {
            Log.GetLog().Debug(caption);
        }

        /// <summary>
        /// 记录异常日志
        /// </summary>
        private void WriteLog(Exception exception)
        {
            Log.GetLog().Caption("Global全局异常捕获").Exception(exception).Error();
        }
    }
}
